package com.ukao.cashregister.ui.statistics;


import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.Utils;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.PieLeftAdapter;
import com.ukao.cashregister.adapter.StatisticDetailsAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.BusinessBean;
import com.ukao.cashregister.bean.ChageInfoBean;
import com.ukao.cashregister.bean.PieBean;
import com.ukao.cashregister.bean.RevenueCntBean;
import com.ukao.cashregister.bean.SummaryBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.dialog.DialogTool;
import com.ukao.cashregister.pesenter.StatisticDetailsPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.StatisticDetailsView;
import com.ukao.cashregister.widget.StateButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.github.mikephil.charting.charts.Chart.PAINT_INFO;
import static com.ukao.cashregister.utils.CheckUtils.isEmptyNumber;


public class StatisticDetailsFragment extends MvpFragment<StatisticDetailsPesenter> implements StatisticDetailsView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;

    List<SummaryBean.PayListBean> mData = new ArrayList<>();
    @BindView(R.id.before_btn)
    TextView beforeBtn;
    @BindView(R.id.date_txt)
    TextView dateTxt;
    @BindView(R.id.date_layout)
    LinearLayout dateLayout;
    @BindView(R.id.later_btn)
    TextView laterBtn;
    @BindView(R.id.current_data_txt)
    TextView currentDataTxt;
    @BindView(R.id.refresh_btn)
    StateButton refreshBtn;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.totalAmt)
    TextView totalAmt;
    @BindView(R.id.left_totalAmt)
    TextView leftTotalAmt;


    @BindView(R.id.order_msg)
    TextView orderMsg;
    @BindView(R.id.user_msg)
    TextView userMsg;
    @BindView(R.id.clothing_msg)
    TextView clothingMsg;
    @BindView(R.id.take_msg)
    TextView takeMsg;
    @BindView(R.id.text)
    TextView text;

    @BindView(R.id.recharge_msg)
    TextView rechargeMsg;
    @BindView(R.id.pie_chart1)
    PieChart pieChart1;
    @BindView(R.id.orderAmt)
    TextView orderAmt;
    @BindView(R.id.couponAmt)
    TextView couponAmt;
    @BindView(R.id.refundAmt)
    TextView refundAmt;
    @BindView(R.id.unpaidDebtAmt)
    TextView unpaidDebtAmt;
    @BindView(R.id.paymentAmt)
    TextView paymentAmt;
    @BindView(R.id.paidDebtAmt)
    TextView paidDebtAmt;
    @BindView(R.id.actualAmt)
    TextView actualAmt;
    @BindView(R.id.orderCnt)
    TextView orderCnt;
    @BindView(R.id.userCnt)
    TextView userCnt;
    @BindView(R.id.takeProCnt)
    TextView takeProCnt;
    @BindView(R.id.sendProCnt)
    TextView sendProCnt;
    @BindView(R.id.rechargeCnt)
    TextView rechargeCnt;
    @BindView(R.id.pie_chart)
    PieChart pieChart;
    @BindView(R.id.chage_totalAmt)
    TextView chageTotalAmt;
    @BindView(R.id.chage_giftAmt)
    TextView chageGiftAmt;
    @BindView(R.id.chage_amount)
    TextView chageAmount;
    @BindView(R.id.chage_refundAmt)
    TextView chageRefundAmt;
    @BindView(R.id.chage_actualAmt)
    TextView chageActualAmt;
    @BindView(R.id.chart_recycler_view)
    RecyclerView chartRecyclerView;
    @BindView(R.id.chart_recycler_view1)
    RecyclerView chartRecyclerView1;
    @BindView(R.id.balanceAmt)
    TextView balanceAmt;
    @BindView(R.id.refBalanceAmt)
    TextView refBalanceAmt;


    private String dateType;
    private String mParam2;
    private String date;
    private Calendar now;
    private String TimeType = "MM月dd日";
    private StatisticDetailsAdapter mStatisticDetails;
    private String unit;
    private String notUnit;
    private List<PieBean> mPieBean = new ArrayList<>();
    private List<PieBean> mPieBean1 = new ArrayList<>();
    private PieLeftAdapter mPieLeftAdapter;
    private PieLeftAdapter mPieLeftAdapter1;


    public static StatisticDetailsFragment newInstance(String param1, String param2) {
        StatisticDetailsFragment fragment = new StatisticDetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            dateType = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected StatisticDetailsPesenter createPresenter() {
        return new StatisticDetailsPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_statistic_details, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    protected void initView() {

        notUnit = getResource().getString(R.string.not_unit);
        unit = getResource().getString(R.string.unit);

        initLinearRecyclerView(chartRecyclerView);
        initLinearRecyclerView(chartRecyclerView1);
        initLinearRecyclerView(recyclerView);
        mPieLeftAdapter = new PieLeftAdapter(_mActivity, mPieBean);
        chartRecyclerView.setAdapter(mPieLeftAdapter);

        mPieLeftAdapter1 = new PieLeftAdapter(_mActivity, mPieBean1);
        mPieLeftAdapter1.setboottomPie(true);
        chartRecyclerView1.setAdapter(mPieLeftAdapter1);

        mStatisticDetails = new StatisticDetailsAdapter(_mActivity, mData);
        recyclerView.setAdapter(mStatisticDetails);
        now = Calendar.getInstance();
        switch (dateType) {
            case "2":
                beforeBtn.setText("上个月");
                laterBtn.setText("下个月");

                break;
        }
        setPie(pieChart);
        setPie(pieChart1);


    }

    private void setPie(PieChart mChart) {


        mChart.setUsePercentValues(true);/*显示成百分比*/
        mChart.getDescription().setEnabled(false);
        mChart.setHoleColor(Color.WHITE);
        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(0);
        mChart.setHoleRadius(40f);//设置圆孔半径
        mChart.setTransparentCircleRadius(61f);
        Paint mInfoPaint = mChart.getPaint(PAINT_INFO);
        mInfoPaint.setTextSize(Utils.convertDpToPixel(20f));
        mChart.setNoDataText("无数据");
        mChart.setNoDataTextColor(getResource().getColor(R.color.black_54));
        mChart.setDrawCenterText(false);
        mChart.setRotationEnabled(true);/*可以手动旋转*/
        mChart.setHighlightPerTapEnabled(false);
        Legend l = mChart.getLegend();
        l.setEnabled(false);
    }

    private void setData(List<PieBean> mPieBean, PieChart mChart, boolean isColor) {


        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        if (!CheckUtils.isEmpty(mPieBean)) {
            for (PieBean pieBean : mPieBean) {

                entries.add(new PieEntry(pieBean.getPayAmount(), ""));

            }

            PieDataSet dataSet = new PieDataSet(entries, "Election Results");
            dataSet.setSliceSpace(0f);
            dataSet.setSelectionShift(5f);/*遮挡间隔*/
            ArrayList<Integer> colors = new ArrayList<Integer>();
            if (isColor) {
                for (int i = 0; i < Constant.VORDIPLOM_COLOR.length; i++) {
                    colors.add(Constant.VORDIPLOM_COLOR[i]);
                }
            } else {
                for (int i = 0; i < Constant.VORDIPLOM_COLOR1.length; i++) {
                    colors.add(Constant.VORDIPLOM_COLOR1[i]);
                }
            }
            dataSet.setColors(colors);
            PieData data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setDrawValues(false);
            mChart.setData(data);
        } else {
            mChart.clear();
            mChart.notifyDataSetChanged();
        }

        mChart.highlightValues(null);
        mChart.invalidate();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        formatDateCustom();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.before_btn, R.id.later_btn, R.id.refresh_btn, R.id.date_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.before_btn:
                switch (dateType) {
                    case "1":/*年月日*/


                        now = MyDateUtils.getBeforeDay(now);
                        formatDateCustom();
                        break;
                    case "2":
                        now = MyDateUtils.getBeforeMouth(now);
                        formatDateCustom();

                        break;
                }


                break;
            case R.id.later_btn:
                switch (dateType) {
                    case "1":/*年月日*/
                        String currenData = MyDateUtils.getDateTime("yyyy-MM—dd");
                        if (currenData.compareTo(date) > 0) {
                            now = MyDateUtils.getAfterDay(now);
                            formatDateCustom();
                        }

                        break;
                    case "2":

                        String currenData1 = MyDateUtils.getDateTime("yyyy-MM");
                        if (currenData1.compareTo(date) > 0) {
                            now = MyDateUtils.getAfterMonth(now);
                            formatDateCustom();
                        }

                        break;
                }

                break;
            case R.id.refresh_btn:
                // currentDataTxt.setText(MyDateUtils.formatDataTime(now.getTime()));
                setRefreshData();
                break;
            case R.id.date_layout:
                String birthday = getText(dateTxt);
                switch (dateType) {
                    case "1":/*月日*/


                        DialogTool.getSingleton().showAnalyzeDatePicker(birthday, TimeType, true, activity, mOnTimeSelectListener);
                        break;
                    case "2":

                        DialogTool.getSingleton().showAnalyzeDatePicker(birthday, TimeType, false, activity, mOnTimeSelectListener);
                        break;
                }


                break;
        }
    }


    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {

            now.setTime(date);
            formatDateCustom();
        }
    };

    private void formatDateCustom() {
        switch (dateType) {
            case "1":/*年月日*/
                TimeType = "yyyy年MM月dd日";
                date = MyDateUtils.formatDateCustom(now.getTime(), "yyyy-MM-dd");
                break;
            case "2":
                TimeType = "yyyy年MM月";
                date = MyDateUtils.formatDateCustom(now.getTime(), "yyyy-MM");
                break;
        }
        currentDataTxt.setText(MyDateUtils.formatDataTime(now.getTime()));
        String datetxt = MyDateUtils.formatDateCustom(now.getTime(), TimeType);
        dateTxt.setText(datetxt);
        setRefreshData();
    }

    public void setRefreshData() {
        mvpPresenter.queryReport(dateType, date);
        mvpPresenter.statisticAnalysis(dateType, date);
        mvpPresenter.revenueCnt(dateType, date);
        mvpPresenter.revenueRecharge(dateType, date);
        mvpPresenter.reportTradeOrder(dateType, date);
        mvpPresenter.reportTradeRecharge(dateType, date);
    }

    @Override
    public void loadFail(String model) {
        T.show(model);
    }


    /**
     * 订单金额信息
     *
     * @param mBusinessBean
     */
    @Override
    public void businessSuccess(BusinessBean mBusinessBean) {
        if (!CheckUtils.isNull(mBusinessBean)) {
            paymentAmt.setText("￥" + isEmptyNumber(mBusinessBean.getPaymentAmt()));/*订单实收金额*/
            couponAmt.setText("￥" + isEmptyNumber(mBusinessBean.getCouponAmt()));/*优惠券金额*/
            totalAmt.setText("￥" + isEmptyNumber(mBusinessBean.getTotalAmt()));/*营收总额*/
            orderAmt.setText("￥" + isEmptyNumber(mBusinessBean.getOrderAmt()));/*订单总额*/
            refBalanceAmt.setText("￥" + isEmptyNumber(mBusinessBean.getRefBalanceAmt()));/*退至余额*/
            unpaidDebtAmt.setText("￥" + isEmptyNumber(mBusinessBean.getUnpaidDebtAmt()));/*未付欠款*/
            paidDebtAmt.setText("￥" + isEmptyNumber(mBusinessBean.getPaidDebtAmt()));/*回收欠款*/
            refundAmt.setText("￥" + isEmptyNumber(mBusinessBean.getRefundAmt()));/*订单退款*/
            actualAmt.setText("￥" + isEmptyNumber(mBusinessBean.getActualAmt()));/*订单实际营收*/
            balanceAmt.setText("(减去会员卡余额支付" + isEmptyNumber(mBusinessBean.getBalanceAmt()) + "元）");/*余额*/

        } else {
            paymentAmt.setText(unit);/*订单实收金额*/
            couponAmt.setText(unit);/*优惠券金额*/
            totalAmt.setText(unit);/*营收总额*/
            orderAmt.setText(unit);/*订单总额*/
            unpaidDebtAmt.setText(unit);/*未付欠款*/
            paidDebtAmt.setText(unit);/*回收欠款*/
            refundAmt.setText(unit);/*订单退款*/
            actualAmt.setText(unit);/*订单实际营收*/
            balanceAmt.setText("(减去会员卡余额支付0.00元)");/*余额*/
        }


    }

    /**
     * 订单数量信息
     */
    @Override
    public void RevenueSucceed(RevenueCntBean mRevenueBean) {
        RevenueCntBean.DataBean mRevenueCntBean = mRevenueBean.getData();
        if (!CheckUtils.isNull(mRevenueCntBean)) {
            rechargeCnt.setText(mRevenueCntBean.getRechargeCnt() + "");/*充值数*/
            userCnt.setText(mRevenueCntBean.getUserCnt() + "");/*新增客户*/
            takeProCnt.setText(mRevenueCntBean.getTakeProCnt() + "");/*收衣数*/
            orderCnt.setText(mRevenueCntBean.getOrderCnt() + "");/*订单数*/
            sendProCnt.setText(mRevenueCntBean.getSendProCnt() + "");/*取衣*/

        } else {
            rechargeCnt.setText(notUnit);/*充值数*/
            userCnt.setText(notUnit);/*新增客户*/
            takeProCnt.setText(notUnit);/*收衣数*/
            orderCnt.setText(notUnit);/*订单数*/
            sendProCnt.setText(notUnit);/*取衣*/
        }

    }


    /**
     * 汇总信息
     */
    @Override
    public void SummarySuccess(SummaryBean mSummaryBean) {

        /*退款*/
        SummaryBean.PayListBean mPayListBean=null;
        if (mSummaryBean.getRefundAmt()!=0){
            mPayListBean = new SummaryBean.PayListBean();
            mPayListBean.setPayMethodText("退款");
            mPayListBean.setAmount(mSummaryBean.getRefundAmt());
        }

        /*手续费*/
        SummaryBean.PayListBean  mServiceChargeBean = null;
        if (mSummaryBean.getFee()!=0){
             mServiceChargeBean = new SummaryBean.PayListBean();
             mServiceChargeBean.setPayMethodText("手续费");
            mServiceChargeBean.setAmount(mSummaryBean.getFee());
        }

        List<SummaryBean.PayListBean> mPayList = mSummaryBean.getPayList();
             mStatisticDetails.getDatas().clear();
           if (mServiceChargeBean!=null){
                mPayList.add(mPayList.size(), mServiceChargeBean);
            }
            if (mPayListBean!=null){
                mPayList.add(mPayList.size(), mPayListBean);
            }

            mStatisticDetails.setDatas(mPayList);
            leftTotalAmt.setText("￥" + isEmptyNumber(mSummaryBean.getTotalAmt()));/*营业总额*/
    }

    @Override
    public void orderPieSucceed(List<PieBean> mPieBean) {
        mPieLeftAdapter.setDatas(mPieBean);
        setData(mPieBean, pieChart, true);
    }

    @Override
    public void chagePieSucceed(List<PieBean> mPieBean) {
        mPieLeftAdapter1.setDatas(mPieBean);
        setData(mPieBean, pieChart1, false);
    }


    /*充值金额信息*/
    @Override
    public void ChageInfoBeanSucceed(ChageInfoBean mRevenueRecharge) {
        ChageInfoBean.DataBean mRevenueCntBean = mRevenueRecharge.getData();
        if (!CheckUtils.isNull(mRevenueCntBean)) {
            chageTotalAmt.setText("￥" + isEmptyNumber(mRevenueCntBean.getTotalAmt()) + "");/*充值总额*/
            chageGiftAmt.setText("￥" + isEmptyNumber(mRevenueCntBean.getGiftAmt()) + "");/*赠送金额*/
            chageActualAmt.setText("￥" + isEmptyNumber(mRevenueCntBean.getActualAmt()) + "");/*储值营收合计*/
            chageRefundAmt.setText("￥" + isEmptyNumber(mRevenueCntBean.getRefundAmt()) + "");/*储值实收金额*/
            chageAmount.setText("￥" + isEmptyNumber(mRevenueCntBean.getAmount()) + "");/*退款*/
        } else {
            chageTotalAmt.setText(unit);
            chageGiftAmt.setText(unit);
            chageActualAmt.setText(unit);
            chageRefundAmt.setText(unit);
            chageAmount.setText(unit);
        }
    }
}
